package com.future.common.interceptor;

import java.lang.reflect.Parameter;

import com.future.common.annotation.JsonBody;
import com.future.common.exception.BadRequestException;
import com.future.common.utils.ValidationUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;

import lombok.extern.slf4j.Slf4j;

/**
 * 该拦截器使得json格式的数据也能作为action的参数
 * 
 * @author ThinkPad
 * @param <T>
 *
 */
@Slf4j
public class JsonInterceptor implements Interceptor {
	private static final String jsonType = "application/json";

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		String contentType = controller.getRequest().getContentType();
		Parameter[] parameters = inv.getMethod().getParameters();
		JsonBody jsonBody = null;
		
		// 判断contentType 是否包含 application/json
		if (contentType != null && contentType.indexOf(jsonType) > -1) {
			for (int i = 0; i < parameters.length; i++) {
				jsonBody = parameters[i].getAnnotation(JsonBody.class);
				if (jsonBody != null) {
					Class<?> T = parameters[i].getType();
					String parameterName = parameters[i].getName();
					Object result = null;
					try {
						String rawData = controller.getRawData();
						log.info("Json Parameter {} valuse is {}",parameterName, rawData);
						result = JsonKit.parse(rawData, T);
					} catch (Exception e) {
						throw new BadRequestException("Bad Request");
					}
					if (result != null && jsonBody.validate()) {
						ValidationUtil.checkValidation(result);
					}
					// 替换原先的参数
					inv.setArg(i, result);
				}
			}
		}
		inv.invoke();
	}

}
